#include "cilent.h"
int main(int argc, char *argv[]) {
    ARGS_CHECK(argc, 3);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "socket");

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);

    int ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    ERROR_CHECK(ret, -1, "connect");

    char buf[4096] = {0};
    Train train;
    fd_set readset;

    while(1) {
        FD_ZERO(&readset);
        FD_SET(STDIN_FILENO, &readset);
        FD_SET(sockfd, &readset);

        select(sockfd + 1, &readset, NULL, NULL, NULL);

        if(FD_ISSET(STDIN_FILENO, &readset)) {
            bzero(buf, sizeof(buf));
            bzero(&train, sizeof(train));

            // 获取用户输入
            if (fgets(buf, sizeof(buf), stdin) == NULL) {
                // 处理EOF（Ctrl+D）
                train.commend = QUIT;
                send(sockfd, &train, sizeof(train.commend) + sizeof(train.length) + train.length, 0);
                break;
            }
            // 移除换行符
            buf[strcspn(buf, "\n")] = '\0';

            if(strlen(buf) == 0) {
                // 空行视为退出
                train.commend = QUIT;
                send(sockfd, &train, sizeof(train.commend) + sizeof(train.length) + train.length, 0);
                break;
            }

            // 解析命令
            if (parse_command(buf, &train) == 0) {
                // 成功解析命令，发送给服务器
                send(sockfd, &train, sizeof(train.commend) + sizeof(train.length) + train.length, 0);
                if(train.commend==PUTS){
                    putsCommand(sockfd,train.data);
                    printf("ok\n");
                }
                if(train.commend==GETS){
                    getsCommand(sockfd);
                    printf("gets ok\n");
                    continue;
                }
                if (train.commend == QUIT) {
                    break;
                }
            }
        }

        if(FD_ISSET(sockfd, &readset)) {
            /* bzero(buf, sizeof(buf)); */
            /* ssize_t sret = recv(sockfd, buf, sizeof(buf), 0); */

            /* if(sret == 0) { */
            /* printf("服务器已断开连接\n"); */
            /* break; */
            /* } else if(sret > 0) { */
            /* printf("服务器响应: %s\n", buf); */
            /* } */
            Train train;
            bzero(&train,sizeof(train));
            int sret=recv(sockfd,&train.commend,sizeof(train.commend),0);
            if(sret == 0) {
                printf("服务器已断开连接\n");
                break;
            }

            if(train.commend==10){
                printf("error command\n");
            }
            recv(sockfd,&train.length,sizeof(train.length),0);
            recv(sockfd,train.data,train.length,0);
            printf("server message: %s\n",train.data);

        }
    }

    close(sockfd);
    return 0;
}
